#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>

int high,width;//游戏画面尺寸
int ball_x,ball_y;//小球坐标
int ball_vx,ball_vy;//小球速度
int speed=0;//控制小球速度
int position_x,position_y;//挡板中心坐标
int radius;//挡板半径
int left,right;//挡板左右边界
int ball_number=0;//碰撞次数
int score=0;//消砖块得分
int brick_x,brick_y;//砖块坐标

void gotoxy(int x,int y)//类似于清屏函数，光标移动到原点位置进行重画
{
    HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD pos;
    pos.X = x;
    pos.Y = y;
    SetConsoleCursorPosition(handle,pos);
}

void startup() {
	high=18;
	width=25;

	ball_x=1;
	ball_y=width/2;

	ball_vx=1;
	ball_vy=1;

	position_x=high;
	position_y=width/2;
	radius=5;
	left=position_y-radius;
	right=position_y+radius;

	brick_x=2;
	brick_y=11;
}

void show() {
	gotoxy(0,0);

	int i,j;
	//system("cls");

	for (i=0;i<=high+1;i++) {
		for (j=0;j<=width;j++) {
			if ((i==ball_x)&&(j==ball_y))
				printf("O");
			else if (j==width)
				printf("|");
			else if (i==high+1)
				printf("-");
			else if ((i==high)&&(j>=left)&&(j<=right))
				printf("*");
			else if ((i==brick_x)&&(j==brick_y))
				printf("M");
			else
				printf(" ");
		}
		printf("\n");
	}
	printf("挡板反弹小球次数:%d\n得分:%d\n",ball_number/6,score);
}


void updateWithoutInput() {

	if (ball_x==high-1) {
		if ((ball_y>=left)&&(ball_y<=right)) {
			ball_number++;
		}
		else {
			printf("Game Over!\n");
			exit(0);
		}
	}
	if (speed<5)
		speed++;
	else if (speed==5) {
	ball_x=ball_x+ball_vx;
	ball_y=ball_y+ball_vy;
	speed=0;


	if (ball_x==0||ball_x==high-1)
		ball_vx=-ball_vx;
	if (ball_y==0||ball_y==width-1)
		ball_vy=-ball_vy;
	speed=0;
	}
	if ((ball_x==brick_x)&&(ball_y==brick_y)) {
		score++;
		brick_x=-1;
		brick_x=rand() % (high-5);
		brick_y=rand() % (width-1);
	}

}

void updateWithInput() {
	char input;
	if (kbhit()) {
		input=getch();
		if (input=='a') {
			position_y--;
			left=position_y-radius;
			right=position_y+radius;
		}
		if (input=='d') {
			position_y++;
			left=position_y-radius;
			right=position_y+radius;
		}
	}
}


int main() {
	startup();
	while(1) {
		show();
		updateWithInput();
		updateWithoutInput();
	}

return 0;
}